package org.ztr.yanai.blog.converter;

import org.jetbrains.annotations.NotNull;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.ztr.yanai.blog.enums.UserStatusEnum;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/11/22 10:00
 * @Description: 枚举类型转换器，将字符串转换为 UserStatusEnum
 * @Version: 1.0
 */
@Component
public class EnumConverter implements Converter<String, UserStatusEnum> {

    @Override
    public UserStatusEnum convert(@NotNull String source) {
        if (source.isEmpty()) {
            return null;
        }
        try {
            int code = Integer.parseInt(source.trim());
            return UserStatusEnum.fromCode(code);
        } catch (NumberFormatException e) {
            // 如果不是数字，尝试按枚举名解析（如 ENABLED）
            try {
                return UserStatusEnum.valueOf(source.trim().toUpperCase());
            } catch (Exception ex) {
                throw new IllegalArgumentException("无法解析用户状态: " + source + "，支持值：0, 1, DISABLED, ENABLED");
            }
        }
    }
}